<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>取消请求</title>
  </head>
  <body>
    <button onclick="getProducts1()">获取商品列表1</button><br />
    <button onclick="getProducts2()">获取商品列表2</button><br />
    <button onclick="cancelReq()">取消请求</button><br />

    <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
    <script>
      const CancelToken = axios.CancelToken;
      let cancel;

      function getProducts1() {
        // 准备发送请求前，取消未完成的请求
        if (typeof cancel === "function") {
          cancel("取消请求");
        }

        axios({
          url: "http://localhost:4000/products1",
          cancelToken: new CancelToken(function executor(c) {
            // executor 函数接收一个 cancel 函数作为参数
            cancel = c;
          }),
        })
          .then((response) => {
            cancel = null;
            console.log("请求1成功了".response);
          })
          .catch((error) => {
            // 处理时取消请求的回调还是错误回调
            if (axios.isCancel(error)) {
              // 异步执行，这里不需要将cancel置为null，他会在其他请求中重新赋值
              // cancel = null;
              console.log("请求1失败了", error.message);
            } else {
              cancel = null;
              console.log("请求1失败了", error.message);
            }
          });
      }

      function getProducts2() {
        // 准备发送请求前，取消未完成的请求
        if (typeof cancel === "function") {
          cancel("取消请求");
        }
        axios({
          url: "http://localhost:4000/products2",
          cancelToken: new CancelToken(function executor(c) {
            // executor 函数接收一个 cancel 函数作为参数
            cancel = c;
          }),
        })
          .then((response) => {
            cancel = null;
            console.log("请求2成功了".response);
          })
          .catch((error) => {
            if (axios.isCancel(error)) {
              console.log("请求2失败了", error.message);
            } else {
              cancel = null;
              console.log("请求2失败了", error.message);
            }
          });
      }

      function cancelReq() {
        if (typeof cancel === "function") {
          cancel("强制取消请求");
        } else {
          console.log("没有可取消的请求");
        }
      }
    </script>
  </body>
</html>
